package com.youlai.system.Task;


import cn.hutool.core.date.DateTime;
import com.youlai.system.plugin.opcua.OpcUaHelper;
import org.eclipse.milo.opcua.sdk.client.OpcUaClient;
import org.eclipse.milo.opcua.sdk.client.subscriptions.ManagedDataItem;
import org.eclipse.milo.opcua.stack.core.UaException;
import org.eclipse.milo.opcua.stack.core.types.builtin.NodeId;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class main2 {

//    // IP配置类
//    public static class IpConfig {
//        @Getter
//        private final String ip;
//        @Getter
//        private final boolean connect;
//        private volatile boolean isConnected;
//
//        public IpConfig(String ip, boolean connect) {
//            this.ip = ip;
//            this.connect = connect;
//            this.isConnected = false;
//        }
//
//        public boolean isConnected() {
//            return isConnected;
//        }
//
//        public void setConnected(boolean connected) {
//            this.isConnected = connected;
//        }
//    }
//
//    public static ThreadPoolTaskExecutor taskExecutor() {
//        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//        // 设置核心线程数
//        executor.setCorePoolSize(4);
//        // 设置最大线程数
//        executor.setMaxPoolSize(16);
//        // 设置队列容量
//        executor.setQueueCapacity(100);
//        // 设置线程活跃时间（秒）
//        executor.setKeepAliveSeconds(10);
//        // 设置线程名称前缀
//        executor.setThreadNamePrefix("MyTaskExecutor-");
//        // 初始化线程池
//        executor.initialize();
//        return executor;
//    }


//    public static void main1(String[] args) {
//
//        OpcUaHelper opcUaHelper = new OpcUaHelper();
//
//        Runnable task1 = () -> {
//
//            String ip = "192.168.0.1";
//
//            OpcUaClient opcUaClient = null;
//            try {
//                opcUaClient = opcUaHelper.Connect(ip);
//            } catch (Exception e) {
//                throw new RuntimeException(e);
//            } finally {
//                System.out.println(ip + " Connect Finish....");
//            }
//        };
//
//        Runnable task2 = () -> {
//            String ip = "192.168.0.2";
//
//            OpcUaClient opcUaClient = null;
//            try{
//                opcUaClient = opcUaHelper.Connect(ip);
//            }catch (Exception e){
//                throw  new RuntimeException(e);
//            }finally {
//                System.out.println(ip + " Connect Finish....");
//            }
//        };
//
//        Runnable task3 = () -> {
//            String ip = "192.168.0.3";
//
//            OpcUaClient opcUaClient = null;
//            try{
//                opcUaClient = opcUaHelper.Connect(ip);
//            }catch (Exception e){
//                throw  new RuntimeException(e);
//            }finally {
//                System.out.println(ip + " Connect Finish....");
//            }
//        };
//
//        //提交到线程池
//        taskExecutor().execute(task1);
//        taskExecutor().execute(task2);
//        taskExecutor().execute(task3);
//
//        //关闭线程池
//        taskExecutor().shutdown();
//    }

    // IP配置类
    // IP配置类
    public static class IpConfig {
        private final String ip;
        private final boolean connect;
        private volatile boolean isConnected;

        public IpConfig(String ip, boolean connect) {
            this.ip = ip;
            this.connect = connect;
            this.isConnected = false;
        }

        public String getIp() {
            return ip;
        }

        public boolean isConnect() {
            return connect;
        }

        public boolean isConnected() {
            return isConnected;
        }

        public void setConnected(boolean connected) {
            this.isConnected = connected;
        }
    }

    // 线程池配置
    private static ThreadPoolTaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(4);
        executor.setMaxPoolSize(16);
        executor.setQueueCapacity(100);
        executor.setKeepAliveSeconds(10);
        executor.setThreadNamePrefix("MyTaskExecutor-");
        executor.initialize();
        return executor;
    }

    // 任务创建方法
    private static Runnable createConnectionTask(IpConfig ipConfig, OpcUaHelperTest opcUaHelperTest, CountDownLatch latch, ExecutorService subscriptionExecutor, List<NodeId> nodeIds) {
        return () -> {
            if (ipConfig.isConnect()) {
                String ip = ipConfig.getIp();
                try {
                    OpcUaClient client = opcUaHelperTest.connect(ip);
                    ipConfig.setConnected(true); // 设置连接状态为成功

                    //开始订阅
                    OpcUaHelper opcUaHelper = new OpcUaHelper();
                    opcUaHelper.Connect();

                } catch (Exception e) {
                    System.err.println("Failed to connect to " + ip + ": " + e.getMessage());
                    ipConfig.setConnected(false); // 设置连接状态为失败
                } finally {
                    System.out.println(ip + " Connect Finish...." + (ipConfig.isConnected() ? " Success" : " Failed"));
                    latch.countDown(); // 任务完成，计数器减一
                }
            } else {
                System.out.println(ipConfig.getIp() + " is not configured to connect.");
                latch.countDown(); // 任务完成，计数器减一
            }
        };
    }

    private static  void subNodeItems(List<String> list) throws UaException, InterruptedException {

        List<String> subList = new ArrayList();

        OpcUaHelper opcUaHelper = new OpcUaHelper();

        subList = list;

        ManagedDataItem.DataValueListener listener = (it, val) ->{
            System.out.println("=====订阅nodeid====== :" + it.getReadValueId().getNodeId().getIdentifier() + DateTime.now());
            System.out.println("=====订阅value===== :" + val.getValue().getValue());
        };

        opcUaHelper.SetSubscriptionItems(subList, listener);
        opcUaHelper.SubscriptionHandler();


        //持续订阅
        Thread.sleep(Long.MAX_VALUE);

    }

    public static void main(String[] args) {
        OpcUaHelperTest opcUaHelperTest = new OpcUaHelperTest();

        // 全局IP配置列表
        List<IpConfig> ipConfigs = new ArrayList<>();
        ipConfigs.add(new IpConfig("192.168.0.1", true));
        ipConfigs.add(new IpConfig("192.168.0.2", true));
        ipConfigs.add(new IpConfig("192.168.0.3", false)); // 不连接


        // 要订阅的节点列表
        List<NodeId> nodeIds = List.of(
                new NodeId(3, "DBLine.Real1"),
                new NodeId(3, "DBLine.Real2")
        );

        // 创建线程池
        ThreadPoolTaskExecutor executor = taskExecutor();

        // 创建订阅线程池
        ExecutorService subscriptionExecutor = Executors.newFixedThreadPool(ipConfigs.size());

        // 创建 CountDownLatch
        CountDownLatch latch = new CountDownLatch(ipConfigs.size());

        // 提交任务到线程池
        for (IpConfig ipConfig : ipConfigs) {
            executor.execute(createConnectionTask(ipConfig, opcUaHelperTest, latch, subscriptionExecutor,nodeIds));
        }

//        // 关闭线程池
//        try {
//            // 等待所有任务完成
//            latch.await(60, TimeUnit.SECONDS); // 等待60秒或直到所有任务完成
//        } catch (InterruptedException e) {
//            System.err.println("Main thread was interrupted while waiting for tasks to complete.");
//            Thread.currentThread().interrupt();
//        } finally {
//            executor.shutdown(); // 关闭连接线程池
//            subscriptionExecutor.shutdown(); // 关闭订阅线程池
//        }

        // 打印最终的连接状态
        for (IpConfig ipConfig : ipConfigs) {
            System.out.println("IP: " + ipConfig.getIp() + " - Connected: " + ipConfig.isConnected());
        }
    }

}
